package org.jsola.hr.common;

import org.apache.poi.ss.formula.functions.T;
import org.jsola.common.StrKit;
import org.jsola.core.IPojo;
import org.jsola.core.Page;
import org.jsola.core.entity.BaseTreeDO;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ListKit {

    @Deprecated
    public static <T> Page<T> listToPage(List<T> list, int pageNo, int pageSize) {
        // 用 PageKit.startPage() 去
        if (pageNo < 1) {
            pageNo = 1;
        }

        if (pageSize < 1) {
            pageSize = 0;
        }

        int start = (pageNo - 1) * pageSize;
        int end = start + pageSize;
        int entityCount = list.size();
        if (start > entityCount) {
            return new Page<>(new ArrayList<T>(), pageNo, pageSize, entityCount);
        }
        end = Math.min(end, entityCount);
        List<T> entities = list.subList(start, end);
        return new Page<>(entities, pageNo, pageSize, entityCount);
    }

    /**
     * 字符串转List<String>
     *
     * @param str ","拼接的字符串
     * @return List<String>
     */
    public static List<String> stringToList(String str) {
        if (StrKit.isEmpty(str)) {
            return new ArrayList<>();
        }
        String[] split = str.split(",");
        return new ArrayList<String>(Arrays.asList(split));
    }


    public static <T> List<T> listTo(List<?> list, Class<T> targetClass) {
        List<T> targetList = new ArrayList<>();
        if(CollectionUtils.isEmpty(list)){
            return targetList;
        }
        for (Object obj : list) {
            assert obj instanceof IPojo;
            targetList.add(((IPojo) obj).to(targetClass));
        }
        return targetList;
    }

    /**
     * 树转平铺
     * @param list
     * @return
     * @param <T>
     */
    public static <T extends BaseTreeDO> List<T> treeToList(List<T> list){
        if (CollectionUtils.isEmpty(list)){
            return list;
        }
        List<T> result = new ArrayList<>();
        result.addAll(list);
        for (T t : list) {
            if (!CollectionUtils.isEmpty(t.getChildList())){
                List<T> child = treeToList(t.getChildList());
                if (!CollectionUtils.isEmpty(child)){
                    result.addAll(child);
                }
            }
        }
        return result;
    }

}
